package com.i72.basic;

import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jiangj
 * @version 1.0.0
 * @ClassName TraceIdHelper.java
 * @Description TODO
 * @createTime 2021年12月29日 10:46:00
 */
public class TraceIdHelper {

    private static final String[]       identifiers        = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    private static String               hexIp;
    private static AtomicInteger atomicInteger      = new AtomicInteger(1000);

    public static String getLocalIPAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            //log.error("getLocalIPAddress failure", e);
            return "127.0.0.1";
        }
    }

    public static String generate() {
        int index = atomicInteger.getAndUpdate(prev -> {
            if (prev >= 9999) return 1000;
            return prev + 1;
        });
        return convertIp() + System.currentTimeMillis() + index + identifiers[(int) (Math.random() * identifiers.length)] + getPid();
    }

    private static String convertIp() {
        if(!StringUtils.isEmpty(hexIp)){
        //if (!StringHelper.isNullOrEmpty(hexIp)) {
            return hexIp;
        }

        //String[] ipSplits = Constant.LOCAL_IP.split("\\.");
        String [] ipSplits = SOAServiceCenter.localIP.split("\\.");
        StringBuilder builder = new StringBuilder();
        for (String ipSplit : ipSplits) {
            builder.append(org.apache.commons.lang3.StringUtils.leftPad(Integer.toHexString(Integer.parseInt(ipSplit)), 2, "0"));
        }
        return hexIp = builder.toString();
    }

    private static String getPid() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            builder.append(identifiers[(int) (Math.random() * identifiers.length)]);
        }
        return builder.toString();
    }


}
